package org.lmind.mis.core.jpa;

import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class EntityManagerQuerier {
	
	private EntityManager entityManager;
	
	private HashMap<Integer, Object> parameters = new HashMap<Integer, Object>();
	
	public EntityManagerQuerier() {
	}
	
	public EntityManagerQuerier(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public void setParameter(int position, Object value)
	{
		parameters.put(position, value);
	}
	
	public List<?> query(String qlString) {
		return query(qlString, -1, -1);
	}
	
	public List<?> query(String qlString, int firstResult, int maxResult) {
		
		Query query = entityManager.createQuery(qlString);
		
		for (int position : parameters.keySet()) {
			query.setParameter(position, parameters.get(parameters));
		}
		if (firstResult >= 0) {
			query.setFirstResult(firstResult);
		}
		if (maxResult >= 0) {
			query.setMaxResults(maxResult);
		}
		
		return query.getResultList();
	}
	
}
